package top.buaarobot.webserver.web.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.buaarobot.webserver.domain.Member;
import top.buaarobot.webserver.repository.MemberRepository;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/api/members")
public class MemberResource{

    private final MemberRepository memberRepository;

    public MemberResource(MemberRepository memberRepository) {
        this.memberRepository = memberRepository;
    }


    @GetMapping(value = "/{game}")
    public ResponseEntity<JSONArray> getAllFilesName(@PathVariable("game") String game){
        Iterable<Member> members =  memberRepository.findAllByOrderByWeight();
        JSONArray response = new JSONArray();
        for(Member member:members){
            JSONObject jsonObject = new JSONObject();
            List<String> games = Arrays.asList(member.getGames().split(";"));
            for(int i=0; i < games.size();i++){
                if(games.get(i).equals(game)){
                    jsonObject.put("name",member.getName());
                    jsonObject.put("academy",member.getAcademy());
                    jsonObject.put("expert",member.getExpert());
                    jsonObject.put("email",member.getEmail());
                    response.add(jsonObject);
                    break;
                }
            }
        }
        return ResponseEntity.ok().body(response);
    }
}
